﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PivotTombstoner.cs" company="XamlNinja">
//   2011 Richard Griffin and Ollie Riches
// </copyright>
// <summary>
//   Pivot Tombstoner.
// </summary>
// <Credits>
//   Original code can be found here http://tombstonehelper.codeplex.com/
//   and additional information here http://msdn.microsoft.com/en-us/library/ff967548(v=vs.92).aspx
// </Credits>
// --------------------------------------------------------------------------------------------------------------------
namespace WP7Contrib.View.Controls.Tombstoner
{
    using System;
    using System.Windows.Controls;

    using Microsoft.Phone.Controls;

    public class ScrollViewerTombstoner : ICanTombstone
    {
        public Type ControlType
        {
            get { return typeof(ScrollViewer); }
        }

        public void Persist<T>(T control, PhoneApplicationPage page) where T : Control
        {
            if (!(control is ScrollViewer))
            {
                return;
            }

            if (string.IsNullOrEmpty(control.Name))
            {
                return;
            }

            try
            {
                var sv = control as ScrollViewer;
                var key = string.Format("ScrollViewer^{0}", control.Name);
                if (page.State.ContainsKey(key))
                {
                    page.State[key] = sv.VerticalOffset;
                }
                else
                {
                    page.State.Add(key, sv.VerticalOffset);
                }
            }
            catch (Exception)
            {
            }
        }

        public void Restore<T>(T control, PhoneApplicationPage page) where T : Control
        {
            if (!(control is ScrollViewer))
            {
                return;
            }

            if (string.IsNullOrEmpty(control.Name))
            {
                return;
            }

            object value;
            var key = string.Format("ScrollViewer^{0}", control.Name);
            if (!page.State.TryGetValue(key, out value))
            {
                return;
            }

            RenderScheduler.ScheduleOnNextRender(() =>
            {
                try
                {
                    var sv = control as ScrollViewer;
                    if (sv == null)
                    {
                        return;
                    }

                    if (page.State.TryGetValue(key, out value))
                    {
                        sv.ScrollToVerticalOffset((double)value);
                        page.State.Remove(key);
                    }
                }
                catch (Exception)
                {
                }
            });
        }
    }
}